package com.chahu.servlet.backend;

import com.alibaba.fastjson.JSON;
import com.chahu.common.Result;
import com.chahu.entity.User;
import com.chahu.service.UserService;
import com.chahu.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/static/backend/login")
public class LoginServlet extends HttpServlet {

    UserService userService;

    @Override
    public void init() throws ServletException {
        userService = new UserServiceImpl();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json; charset=utf-8");
        
        String user = req.getParameter("username");
        String pwd = req.getParameter("password");
        
        boolean auth = userService.login(user, pwd);
        if(auth) {
        	User admin = new User();
        	admin.setUsername(user);
        	admin.setPassword(pwd);
        	req.getSession().setAttribute("admin", admin);
        	resp.sendRedirect("index.html");
        	return;
        }
        resp.sendRedirect("login.html");
    }
}
